package com.aopeng.controller;

import com.aopeng.entity.AopengExamination;
import com.aopeng.entity.AopengUser;
import com.aopeng.mapper.AopengExaminationMapper;
import com.aopeng.mapper.AopengSchoolMapper;
import com.aopeng.mapper.AopengUserMapper;
import com.aopeng.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * @author 谢辉
 * @description 登录控制器
 * @data 2020/7/11
 */

@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private AopengUserMapper aopengUserMapper;

    @Autowired
    private AopengSchoolMapper aopengSchoolMapper;

    //返回到登录页
    @GetMapping
    public String loginPage(){
        return "admin/login";
    }

    //登录校验成功后跳转得首页
    @RequestMapping(value = "/indexpage",method = RequestMethod.POST)
    public String indexPage(@RequestParam String username, @RequestParam String loginPassword,
                            RedirectAttributes attributes, HttpSession session){
        //查询用户
        AopengUser user = aopengUserMapper.findUsernameByLoginPassword(username, MD5Utils.code(loginPassword));

        if (user!=null){
            session.setAttribute("user",user);
            //user.setAvatar();
            return "redirect:/admin/in";
        }else {
            attributes.addFlashAttribute("message", "用户名或密码错误");
            return "redirect:/admin";
        }
    }

    @RequestMapping(value = "/in",method = RequestMethod.GET)
    public String index(Model model){
        model.addAttribute("south",aopengSchoolMapper.findSouthSchoolById());  //查询南方院校总数
        model.addAttribute("north",aopengSchoolMapper.findNorthSchoolById());  //查询北方院校总数
        model.addAttribute("southPaper",aopengSchoolMapper.findSouthSchoolTestPaper()); //查询南方院校试卷总数
        model.addAttribute("northPaper",aopengSchoolMapper.findNorthSchoolTestPaper()); //查询北方院校试卷总数

        return "admin/index";
    }
}
